import tkinter as tk
from threading import Thread
from tkinter.ttk import Treeview
import requests
from tkinter.filedialog import asksaveasfilename
from crawler import Crawler
from tkinter.messagebox import showerror, showinfo
import re
import os


class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('vip音乐破解软件')
        self.iconbitmap('favicon.ico')
        self.filters = ['name', 'url', 'id']
        self.types = {'网易(推荐)': 'netease', 'ＱＱ': 'qq', '酷狗': 'kugou', '酷我': 'kuwo', '千千': 'baidu', '一听': '1ting',
                      '咪咕': 'migu', '荔枝': 'lizhi', '蜻蜓': 'qingting', '喜马拉雅': 'ximalaya', '5sing原创': '5singyc',
                      '5sing翻唱': '5singfc', '全民K歌': 'kg'}
        self.input_var = tk.StringVar()
        self.type_var = tk.StringVar()
        self.type_var.set('netease')
        # self.crawl_results = []
        self.page = 1
        self.tree: Treeview = None
        self.downloaded_songs = []
    
    def create_page(self):
        tk.Label(self, text='搜索方式:').grid(row=0, column=0)
        tk.Radiobutton(self, text='音乐名称', variable=self.filter_var, value='name').grid(row=0, column=1)
        tk.Radiobutton(self, text='音乐ID', variable=self.filter_var, value='id').grid(row=0, column=2)
        tk.Radiobutton(self, text='音乐地址', variable=self.filter_var, value='url').grid(row=0, column=3)

        frame = tk.Frame(self)
        tk.Label(frame, text='搜索内容:').grid(row=0, column=0)
        tk.Entry(frame, textvariable=self.input_var, width=30, font=('宋体', 18)).grid(row=0, column=1)
        frame.grid(row=1, column=0, columnspan=5)

        for key, value in self.types.items():
            # print(key, value)
            if list(self.types.keys()).index(key) < 6:
                tk.Radiobutton(self, text=key, variable=self.type_var, value=value).grid(row=2, column=list(
                    self.types.keys()).index(key))
            else:
                tk.Radiobutton(self, text=key, variable=self.type_var, value=value).grid(row=3, column=list(
                    self.types.keys()).index(key) - 6)

        frame2 = tk.Frame(self)
        tk.Button(frame2, text='查    询    歌    曲', width=50, command=Thread(target=self.get_data).start).grid(row=0,
                                                                                                                 column=0)
        frame2.grid(row=4, column=0, columnspan=6)

        self.tree = Treeview(self, columns=['1', '2', '3'], show='headings', height=10)
        self.tree.grid(row=5, column=0, columnspan=6)
        self.tree.column('1', width=130, anchor='center')
        self.tree.column('2', width=160, anchor='center')
        self.tree.column('3', width=100, anchor='center')
        self.tree.heading('1', text='作者')
        self.tree.heading('2', text='标题')
        self.tree.heading('3', text='歌曲id号')
        # self.tree.configure(yscrollcommand=scrollbar.set)

        frame3 = tk.Frame(self)
        tk.Button(frame3, text='加载新歌曲', width=25, command=Thread(target=self.get_data, kwargs={'new': True}).start).grid(row=0, column=0, columnspan=3)
        tk.Button(frame3, text='下载选中的歌曲', width=25, command=Thread(target=self.download_music).start).grid(row=0, column=3, columnspan=3)
        frame3.grid(row=6, column=0, columnspan=6)


    def determine_filter(self, content):
        if re.match('^\d+$', content):
            return 'id'
        elif re.match('[a-zA-z]+://[^s]*', content):
            return 'url'
        else:
            return 'name'
            
    def get_data(self, new=False):
        if not new:
            self.page = 1
            for children in self.tree.get_children():
                # print(children)
                self.tree.delete(children)
        if not self.input_var.get():
            showerror('error', '请输入歌曲！')
            return
        crawler = Crawler(input_=self.input_var.get(),
                          filter_=self.determine_filter(self.input_var.get()),
                          type_=self.type_var.get())
        results = crawler.crawler_main(page=self.page)
        for result in results:
            self.tree.insert("", tk.END, values=(result['author'], result['title'], result['song_id']))
            self.downloaded_songs.append(result)
        self.page += 1

    def find_song_url(self, song_id):
        for song in self.downloaded_songs:
            if song['song_id'] == song_id:
                return song['mp3_url']
        else:
            return

    def download_music(self, online=False):
        focus_id = self.tree.focus()
        item = self.tree.item(focus_id)
        if not item['values']:
            showerror('vip音乐破解软件', '未选中歌曲！')
            return
        song_name = item['values'][1]
        song_id = item['values'][2]
        song_url = self.find_song_url(song_id)
        if song_url:
            song_content = requests.get(song_url).content
            if not online:
                filename = asksaveasfilename(initialfile=f'{song_name}.{song_url.split(".")[-1]}', filetypes=[('MP3', '*.mp3')])
                if filename:
                    with open(filename, 'wb') as f:
                        f.write(song_content)
                    showinfo('vip音乐破解软件', '下载成功')
                return
            else:
                username = os.getlogin()
                path = f'C:\\Users\\{username}\\Temp\\song.{song_url.split(".")[-1]}'
                with open(path, 'wb') as f:
                    f.write(song_content)
                
        

    def main(self):
        self.create_page()
        self.mainloop()


window = Window()
window.main()
